#!/bin/bash 

pwd=`echo $PWD`
dir="miniLinux"
fs="initramfs"
qemu="qemu-system-x86_64"
kernel=`ls /boot/vmlinuz*|tail -n1`

if [ -d $dir ]
then 
  echo "$dir exists"
  echo "stopping script..."
  exit 1
fi

mkdir -p $dir/$fs

cd $dir/$fs
mkdir -pv bin lib dev etc mnt/root proc root sbin sys etc/init.d

echo "Getting Busybox..."
cd bin
wget "https://busybox.net/downloads/binaries/latest/busybox-x86_64" -O busybox
chmod +x busybox

echo "Linking Busybox Apps..."
./busybox  --help | \
sed -e '1,/^Currently defined functions:/d' \
    -e 's/[ \t]//g' -e 's/,$//' -e 's/,/\n/g' | \
while read app ; do
  if [ "$app" != "" ]; then
    printf "linking %-12s ...\n" "$app"
    ln -sf "./busybox" "$app"
    ls -ld "$app"
  fi
done
cp init /sbin/init

echo "Creating init script..."
cd $pwd/$dir/$fs
echo 
cat << EOF > init
#!/bin/sh

mount -t devtmpfs none /dev
/bin/mount -t proc none /proc
/bin/mount -t sysfs sysfs /sys
/bin/mdev -s

sleep 3
clear
echo "============Welcome============"
/bin/ash --login

echo "Goodbye..."
read
# Clean up.
umount /proc
umount /sys
umount /dev
EOF

chmod 755 init

find . -print0 | cpio --null -ov --format=newc > ../initrd.cpio

cd $pwd/$dir
cp $kernel ./kernel

$qemu -kernel kernel -initrd initrd.cpio